#include "03_lib.h"
#include <malloc.h>
int empty(sqlink* L)
{
	if(*L == NULL)
	{
		return 0;
	}
	return 1;
}
sqlink* CreateList(void)
{
	sqlink* L = (sqlink*)malloc(sizeof(sqlink));
	*L = NULL;
	return L;
}
int Length(sqlink* L)
{
	if(empty(L) == 0)
	{
		return 0;
	}
	int length = 0;
	sqlink l = *L;
	while(l != NULL)
	{
		l = l->next;
		length++;
	}
	return length;
}
void freeList(sqlink L)
{
	if(L->next != NULL)
	{
		freeList(L->next);
	}
	free(L);
}
void ClearList(sqlink* L)
{
	if(empty(L) == 0)
	{
		return;
	}
	freeList(*L);
}
int GetList(sqlink* L,int index)
{
	if(empty(L) == 0)
	{
		return -1;
	}
	index--;
	int i = 0;
	sqlink l = *L;
	while(l->next != NULL)
	{
		if(i == index)
		{
			return l->data;
		}
		l = l->next;
		i++;
	}
	return -1;
}
int LocateList(sqlink* L,int value)
{
	if(empty(L) == 0)
	{
		return -1;
	}
	int i = 1;
	sqlink l = *L;
	while(l->next != NULL);
	{
		if(l->data == value)
		{
			return i;
		}
		i++;
	}
	return -1;
}
void PushList(sqlink* L,int value)
{
	if(empty(L) == 0)
	{
		*L = (sqlink)malloc(sizeof(sqlist));
		(*L)->data = value;
		(*L)->next = NULL;
		return;
	}
	sqlink l = *L;
	while(1)
	{
		if(l->next == NULL)
		{
			l->next = (sqlink)malloc(sizeof(sqlist));
			l->next->data = value;
			l->next->next = NULL;
			return;
		}
		l = l->next;
	}
}
void InsertList(sqlink* L,int value,int index)
{
	sqlink l = NULL;
	if(index == 1)
	{
		l = (sqlink)malloc(sizeof(sqlist));
		l->data = value;
		l->next = *L;
		*L = l;
		return;
	}
	int i = 1;
	sqlink l1 = *L;
	do{
		if(index == (i + 1))
		{
			l = (sqlink)malloc(sizeof(sqlist));
			l->data = value;
			l->next = l1->next;
			l1->next = l;
			return;
		}
		i++;
		l1 = l1->next;
	}
	while(l1->next != NULL);
}
void DeleteList(sqlink* L,int index)
{
	if(empty(L) == 0)
	{
		return;
	}
	sqlink l = NULL;
	if(index == 1)
	{
		l = (*L)->next;
		free(*L);
		*L = l;
		return;
	}
	l = *L;
	int i = 1;
	while(l->next != NULL)
	{
		if(i == (index - 1))
		{
			sqlink temp = l->next->next;
			free(l->next);
			l->next = temp;
		}
		i++;
	}
}
void PrintList(sqlink* L)
{
	if(empty(L) == 0)
	{
		return;
	}
	sqlink l = *L;
	int i = 1;
	do
	{
		printf("data[%d] = %d\n",i,l->data);
		l = l->next;
		i++;
	}
	while(l != NULL);
}
void reverse(sqlink* L)
{
	if(empty(L) == 0)
	{
		return;
	}
	sqlink l = *L,reverse = NULL,last = *L,temp;
	do{
		temp = l;
		l = l->next;
		if(reverse == NULL)
		{
			reverse = temp;
		}
		else
		{
			temp->next = reverse;
			reverse = temp;
		}
	}
	while(l != NULL);
	*L = reverse;
	last->next = NULL;

}
void merge(sqlink * L_left,sqlink * L_right)
{
	if(empty(L_left) == 0 || empty(L_right) == 0)
	{
		return;
	}
	sqlink l = *L_left;
	while(l != NULL)
	{
		if(l->next == NULL)
		{
			l->next = *L_right;
		}
		l = l->next;
	}
	*L_right = *L_left;
}
